<?php
namespace Todo\Service;

/**
 * Created by PhpStorm.
 * User: yepanpan
 * Date: 2016/8/8
 * Time: 17:08
 */
class FormatService extends BaseService
{
    private static $__INSTANCE = null;
    private $__userCache = array();
    private $__fileCache = array();

    public static function getInstance(){
        if(!self::$__INSTANCE) self::$__INSTANCE = new FormatService();

        return self::$__INSTANCE;
    }

    /**
     * 格式化数据
     * @param array $row 当前行数据
     * @param array $column 字段配置
     * @return mixed|string
     */
   public function format($row, $column){
       $value = $row[$column['name']];
       $type = strtolower($column['type']);
       switch ($type){
           case 'relation':
               if($value) $value = $this->formatRelation1($value, $column['option']['model'], $column['option']['title']);
               else if( $column['option']['table']) $value = $this->formatRelation2($row['id'], $column['option']);
               else $value = '无';
               break;
           case 'dict':
               $value = $this->formatDict($value, $column['option']['dict']);
               break;
           case 'date':
               $format = $column['option']['format'] ? $column['option']['format'] : 'Y-m-d';
           case 'datetime':
               $format = $column['option']['format'] ? $column['option']['format'] : 'Y-m-d H:i:s';
               $value = $this->formatDate($value, $format);
               break;
           case 'user':
               $value = $this->formatUser($value);
               break;
           case 'file':
               $value = $this->formatFile($value,$column['option']['field']);
               break;
           case 'size':
               $value = $this->formatSize($value);
               break;
           default;
               break;
       }
       return $value;
   }

    /** 格式化关联数据
     * @param $val 当前数据的关联值
     * @param int string $model 被关联的模型
     * @param string $field 要取的被关联的模型字段
     * ---------------以下是通过中间表多对多需要的参数
     * @param string $table 中间表
     * @param string $fkey 关联表中当前数据的主键
     * @param string $rkey 关联表中被关联模型的主键
     * ---------------以上是通过中间表多对多需要的参数
     * @return mixed|string
     */
    public function formatRelation($val, $model, $field='title', $table='', $fkey='', $rkey=''){
        //没有关联表，直接取值
        if(!$table) return $this->formatRelation1($val, $model,$field);

        //有关联表，先读取中间关联表，再取值
        $value = '';
        $rlist = M($table)->where(array($fkey=>$val))->select();
        if(!$rlist) return $value;

        foreach ($rlist as $row){
            $value .= ','. $this->formatRelation1($row[$rkey], $model, $field);
        }
        $value = substr($value, 1);
        return $value;
    }

    /**
     * @param $value
     * @param $row
     * @param $column
     * @return mixed|string|void
     */
    public function formatRelation2($key, $option){
        $value = '';
        $rlist = M($option['table'])->where(array($option['key']=>$key))->select();
        if(!$rlist) return $value;

        foreach ($rlist as $row){
            $value .= ','. $this->formatRelation1($row[$option['field']], $option['model'], $option['title']);
        }
        $value = substr($value, 1);
        return $value;
    }

    /** 格式化属性关联关系字段
     * @param int $val 值
     * @param string $model 模型
     * @param string $field 字段
     * @return mixed
     */
    public function formatRelation1($val, $model, $field='title'){
        return D($model)->keyFind($val, $field);
    }

    /**
     * 格式化数据字典
     * @param string $val 值
     * @param string $dictCode 数据字典代码
     * @return mixed
     */
    public function formatDict($val, $dictCode){
        return DictService::getInstance()->getDictTitle($dictCode, $val);
    }

    /**
     * 格式化用户
     * @param int $userId 用户ID
     * @return string
     */
    public function formatUser($userId){
        $userInfo = $this->__userCache[$userId];
        if(!$userInfo){
            $userInfo = D('Todo/Sys/User')->keyFind($userId);
            $this->__userCache[$userId] = $userInfo;
        }
        if($userInfo) return $userInfo['nickname'];
        return '';
    }

    /**
     * 格式化时间
     * @param int $time 时间
     * @param string $format=Y-m-d 格式
     * @return string
     */
    public function formatDate($time, $format='Y-m-d'){
        return date($format, $time);
    }

    /**
     * 格式化文件
     * @param int $fileId 文件ID
     * @param string $field=path 字段,为空返回整个数组
     * @return mixed
     */
    public function formatFile($fileId, $field='path'){

        $fileInfo = $this->__fileCache[$fileId];
        if(!$fileInfo){
            $fileInfo = D('Todo/Sys/Files')->keyFind($fileId);
            $this->__fileCache[$fileId] = $fileInfo;
        }
       return $field ? $fileInfo[$field] : $fileInfo;
    }

    /**
     * 格式化文件大小
     * @param int $size 文件字节数
     * @return mixed
     */
    public function formatSize($size){
        return Files::format_bytes($size);
    }
}